package com.lvmama.rhino.job.comment;

import java.util.List;

import org.mortbay.log.Log;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.job.BaseQuartzJobBean;
import com.lvmama.rhino.pojo.comment.entity.vo.PredictFavorRateCalcJobVO;
import com.lvmama.rhino.service.comment.PredictCalcService;

/**
 * 好评率预测计算任务
 */

public class PredictFavorRateCalcJob extends BaseQuartzJobBean  {

    @Autowired
    private PredictCalcService predictCalcService;

    private static final int size = 10000;

    public void invoke(JobExecutionContext context) {
        try {
            // 1.删除表数据
            Log.info("1.deleteLastPredictData start");
            predictCalcService.deleteLastPredictData();
            Log.info("1.deleteLastPredictData end");

            int currentPage = 1;
            PageInfo<PredictFavorRateCalcJobVO> pageList;
            do {
                PageHelper.startPage(currentPage, size);
                // 2.查询填充表数据
                Log.info("2.queryPredictFavorRateData start:" + currentPage + "/" + size);
                pageList = new PageInfo<>(predictCalcService.queryPredictFavorRateData());
                if (null == pageList || CollectionUtils.isEmpty(pageList.getList())) {
                    Log.warn("calcPredictFavorRate queryPredictFavorRateData null");
                    break;
                }
                Log.info("2.queryPredictFavorRateData end:" + currentPage + "/" + size);
                executeJob(pageList.getList());
                currentPage++;
            } while (!pageList.isIsLastPage());
        } catch (Exception e) {
            e.printStackTrace();
            Log.warn("PredictFavorRateCalcJob error:" + e.getMessage(), e);
        }
    }

    private void executeJob(List<PredictFavorRateCalcJobVO> predictList) throws Exception {

        // 3.计算上周好评率
        Log.info("3.queryLastWeekFavorRate start");
        predictCalcService.queryLastWeekFavorRate(predictList);
        Log.info("3.queryLastWeekFavorRate end");

        // 4.批量填充表数据
        Log.info("4.savePredictFavorRateData start");
        predictCalcService.savePredictFavorRateData(predictList);
        Log.info("4.savePredictFavorRateData end");
    }
}
